<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { RouterView } from 'vue-router'
import Toast from './components/Toast.vue'
import websocketService from './services/websocketService'
import { getUserId, getAuthToken } from './utils/authUtils'

// 通知Toast状态
const toastVisible = ref(false)
const toastMessage = ref('')
const toastType = ref('info')

// 处理WebSocket通知消息
const handleWebSocketNotification = (message) => {
  console.log('APP.VUE收到通知:', message)
  
  if (!message || !message.content) {
    console.warn('APP.VUE: 通知消息格式无效', message)
    return
  }
  
  // 设置通知类型
  let type = 'info'
  if (message.notificationType === 'message') {
    type = 'success'
    console.log('APP.VUE: 设置为消息通知类型')
  } else if (message.notificationType === 'transaction') {
    type = 'warning'
    console.log('APP.VUE: 设置为交易通知类型')
  } else if (message.notificationType === 'favorite') {
    type = 'info'
    console.log('APP.VUE: 设置为收藏通知类型')
  } else if (message.type === 'error' || message.type === 'ERROR') {
    type = 'error'
    console.log('APP.VUE: 设置为错误通知类型')
  }
  
  // 显示Toast通知
  toastMessage.value = message.content
  toastType.value = type
  toastVisible.value = true
  
  // 打印日志
  console.log(`APP.VUE 显示通知[${type}]: ${message.content}`)
}

// WebSocket连接
const connectWebSocket = () => {
  console.log('App.vue: 尝试连接WebSocket');
  
  // 获取WebSocket当前状态
  const wsStatus = websocketService.getConnectionStatus();
  
  // 如果WebSocket正在连接中，不要重复操作
  if (wsStatus.isConnecting) {
    console.log('App.vue: WebSocket正在连接中，不重复连接');
    return;
  }
  
  try {
    // 直接从localStorage获取用户ID
    const userData = JSON.parse(localStorage.getItem('user') || '{}');
    const userId = userData.id || localStorage.getItem('userId');
    
    if (userId) {
      console.log('App.vue: 从localStorage获取到用户ID:', userId);
      
      // 如果之前有连接，确保先完全断开
      if (wsStatus.isConnected || wsStatus.socketState !== -1) {
        console.log('App.vue: 先断开现有连接');
        websocketService.disconnect();
        
        // 延迟1.5秒后重新连接
        setTimeout(() => {
          console.log('App.vue: 延迟后重新连接WebSocket');
          websocketService.connect(userId);
        }, 1500);
      } else {
        // 直接连接
        console.log('App.vue: 直接连接WebSocket');
        websocketService.connect(userId);
      }
    } else {
      console.log('App.vue: localStorage中未找到用户ID，不连接WebSocket');
    }
  } catch (error) {
    console.error('App.vue: 连接WebSocket失败:', error);
  }
};

// 监听localStorage变化
const setupStorageListener = () => {
  console.log('APP.VUE: 设置localStorage监听')
  window.addEventListener('storage', (event) => {
    if (event.key === 'user' || event.key === 'token') {
      console.log(`APP.VUE: localStorage变化 - ${event.key}已更新`)
      connectWebSocket()
    }
  })
}

// 注册WebSocket消息处理
onMounted(() => {
  console.log('APP.VUE: 组件挂载，注册通知处理器')
  
  // 添加专用通知处理
  websocketService.addNotificationHandler(handleWebSocketNotification)
  
  // 设置localStorage监听
  setupStorageListener()
  
  // 尝试连接
  connectWebSocket()
  
  // 设置轮询检查用户ID和WebSocket连接
  const intervalId = setInterval(() => {
    const userId = getUserId()
    const wsStatus = websocketService.getConnectionStatus()
    
    console.log('APP.VUE: 定时检查 - 用户ID:', userId, 'WebSocket状态:', wsStatus.isConnected ? '已连接' : '未连接')
    
    if (userId && !wsStatus.isConnected && !wsStatus.isConnecting) {
      console.log('APP.VUE: 发现用户ID存在但WebSocket未连接，尝试重新连接')
      connectWebSocket()
    }
  }, 10000) // 每10秒检查一次
  
  // 在组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(intervalId)
  })
})

// 移除事件监听
onUnmounted(() => {
  console.log('APP.VUE: 组件卸载，移除通知处理器')
  websocketService.removeNotificationHandler(handleWebSocketNotification)
  
  // 移除localStorage监听
  window.removeEventListener('storage', setupStorageListener)
})

// 关闭Toast
const handleCloseToast = () => {
  console.log('APP.VUE: 关闭Toast')
  toastVisible.value = false
}
</script>

<template>
  <RouterView />
  
  <!-- 全局通知Toast -->
  <Toast 
    :visible="toastVisible" 
    :message="toastMessage" 
    :type="toastType" 
    :duration="3000"
    @close="handleCloseToast" 
  />
</template>

<style>
body {
  font-family: 'Arial', 'Microsoft YaHei', sans-serif;
  margin: 0;
  padding: 0;
  background-color: #f9fafb;
  color: #1f2937;
}

* {
  box-sizing: border-box;
}
</style>
